//
//  ViewController.m
//  oilApp
//
//  Created by 王辩 on 2018/10/31.
//  Copyright © 2017年 王辩. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>
#import "AppConstant.h"
#import "MBProgressHUD.h"
#import "CustomSlideView.h"
#import "FDAlertView.h"
#import "AFNetworking.h"
#import <CoreLocation/CoreLocation.h>
#import <AlipaySDK/AlipaySDK.h>
#import "WXApiRequestHandler.h"
#import "WXApiManager.h"
//#import "RespForWeChatViewController.h"
#import "WechatAuthSDK.h"

#import "APAuthInfo.h"
#import "APOrderInfo.h"
#import "APRSASigner.h"

#define adsViewWidth 235.0*(APPScreenBoundsWidth/320.0)
#define RatioValue  (APPScreenBoundsHeight-118)/450.0
#define APPScreenBoundsHeight [UIScreen mainScreen].bounds.size.height
#define APPScreenBoundsWidth [UIScreen mainScreen].bounds.size.width

@interface ViewController ()<WKNavigationDelegate, WKUIDelegate,SlideCardViewDelegate,FDAlertViewDelegate,CLLocationManagerDelegate>
{
    CustomSlideView *_slide;
    CLLocation *currentLocation;
    NSString *currentAddress;
    NSString *destinationAddress;
    MBProgressHUD *hud;
}
@property (strong, nonatomic) WKWebView *webView;
@property (nonatomic ,strong) NSMutableArray *data;
@property (nonatomic, strong) CLLocationManager* locationManager;

@end

@implementation ViewController
{
//    MBProgressHUD *hud;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self getLocation];
    
    currentAddress = nil;
    destinationAddress = nil;
    self.data = [[NSMutableArray alloc]init];
    
    [self sendRequest];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = [[WKUserContentController alloc]init];
    WKPreferences *preferences = [[WKPreferences alloc]init];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    configuration.preferences = preferences;
    
    _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, NAVI_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT) configuration:configuration];
    if (@available(iOS 11.0, *)) {
        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    _webView.navigationDelegate = self;
    _webView.scrollView.bounces = false;
    [self.view addSubview:_webView];
    [self addMBProgressView];

    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://202.103.63.6:6100/oil/index.html#/index"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0f];
    [_webView loadRequest:request];
    
}

-(void)addMBProgressView
{
    hud = [MBProgressHUD showHUDAddedTo:_webView animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = @"正在加载...";
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC);
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

    });
}

-(void)getLocation{
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    [self.locationManager requestAlwaysAuthorization];
    [self.locationManager requestWhenInUseAuthorization];
    
    //设置寻址精度
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 5.0;
    [self.locationManager startUpdatingLocation];
}

-(void)sendRequest{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *params = @{};
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:@"http://202.103.63.6:6100/oil/gas/all.htm?params=" parameters:params headers:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if([@"200" isEqualToString:[NSString stringWithFormat:@"%@",dic[@"code"]]] && [dic[@"message"] isEqualToString:@"OK"]){
            self.data = dic[@"data"];
        }
        
    } failure:^(NSURLSessionTask *operation, NSError *error) {
        NSLog(@"返回错误: %@", error);
    }];
}

-(void)popCardView{
    if(self.data.count > 0){
        CGRect rect = {{lrintf((APPScreenBoundsWidth-adsViewWidth)/2.0),118},{lrintf(adsViewWidth) , APPScreenBoundsHeight-336}};
        
        _slide = [[CustomSlideView alloc]initWithFrame:rect AndzMarginValue:9/(RatioValue) AndxMarginValue:11/(RatioValue) AndalphaValue:1 AndangleValue:2000];
        _slide.delegate = self;
        [_slide addCardDataWithArray:self.data];
        _slide.backgroundColor = [UIColor clearColor];
        
        FDAlertView *alert = [[FDAlertView alloc] init];
        alert.contentView = _slide;
        [alert show];
    }else{
        FDAlertView *alert = [[FDAlertView alloc] initWithTitle:@"暂无数据" icon:nil message:@"请联系管理员" delegate:self buttonTitles:@"确定", nil];
        [alert setMessageColor:[UIColor redColor] fontSize:0];
        [alert show];
    }
}

//- (IBAction)popCardView:(id)sender {
////    self.view.backgroundColor = [UIColor blackColor];
////    self.view.alpha = 0.7;
////    [self.view addSubview:_slide];
//
//
//
//}

-(void)goNavBtnClick:(NSString *)longitude andLatitude:(NSString *)latitude{
    NSLog(@"longitude====%@,latitude====%@",longitude,latitude);
    
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLLocation *cl = [[CLLocation alloc] initWithLatitude:[latitude floatValue] longitude:[longitude floatValue]];
    [clGeoCoder reverseGeocodeLocation:cl completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *placeMark in placemarks) {

            destinationAddress = [NSString stringWithFormat:@"%@%@%@",placeMark.locality,placeMark.subLocality,placeMark.name];

            if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"iosamap://"]]) {
                // 起点为“我的位置”，终点为后台返回的坐标
                NSString *urlString = [[NSString stringWithFormat:@"iosamap://path?sourceApplication=applicationName&sid=BGVIS1&slat=%f&slon=%f&sname=%@&did=BGVIS2&dlat=%@&dlon=%@&dname=%@&dev=0&m=0&t=0",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude,currentAddress,latitude,longitude,destinationAddress] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                NSURL *url = [NSURL URLWithString:urlString];
                [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {

                }];
            }else{
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请下载高德地图" message:nil preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                }];
                [alertController addAction:actionOK];
                [self presentViewController:alertController animated:YES completion:nil];
            }
        }
    }];
    
}

-(void)getCurrentAddress:(double)longitude Andlat:(double)latitude
{
    CLGeocoder *clGeoCoder = [[CLGeocoder alloc] init];
    CLLocation *cl = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
    [clGeoCoder reverseGeocodeLocation:cl completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        for (CLPlacemark *placeMark in placemarks) {
            currentAddress = [NSString stringWithFormat:@"%@%@%@",placeMark.locality,placeMark.subLocality,placeMark.name];
        }
    }];
}

#pragma mark- 代理
- (void)alertView:(FDAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"%ld", (long)buttonIndex);
}

-(void)slideCardViewDidEndScrollIndex:(NSInteger)index
{
//    NSLog(@"__end__%ld",index);
//    _slide.label.text = [NSString stringWithFormat:@"%ld",index];
}

-(void)slideCardViewDidSlectIndex:(NSInteger)index
{
//    NSLog(@"__select__%ld",index);
}

-(void)slideCardViewDidScrollAllPage:(NSInteger)page AndIndex:(NSInteger)index
{
    
    //判断是否为第一页
    //    if(page == index){
    //        if (self.comeBackFirstMessageButton.frame.origin.y<APPScreenBoundsHeight) {
    //            [UIView animateWithDuration:0.8 animations:^{
    //                self.comeBackFirstMessageButton.center = CGPointMake(self.comeBackFirstMessageButton.center.x, self.comeBackFirstMessageButton.center.y+self.comeBackFirstMessageButton.frame.size.height);
    //            }];
    //        }
    //    }else{
    //        if (self.comeBackFirstMessageButton.frame.origin.y>=APPScreenBoundsHeight) {
    //            [UIView animateWithDuration:0.8 animations:^{
    //                self.comeBackFirstMessageButton.center = CGPointMake(self.comeBackFirstMessageButton.center.x, self.comeBackFirstMessageButton.center.y-self.comeBackFirstMessageButton.frame.size.height);
    //            }];
    //        }
    //    }
    
    //提醒已是最后一条消息,由透明慢慢显现
    //    if (_curPage == _totalPage && slideImageView.scrollView.contentOffset.y<0) {
    //        self.lastMessageLabel.alpha = -(slideImageView.scrollView.contentOffset.y/50.0);
    //    }
}



/**
 *  页面开始加载时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  当内容开始返回时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  页面加载完成之后调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 */
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    [MBProgressHUD hideHUDForView:_webView animated:YES];
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  加载失败时调用
 *
 *  @param webView    实现该代理的webview
 *  @param navigation 当前navigation
 *  @param error      错误
 */
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    //    hud = [MBProgressHUD showHUDAddedTo:_webView animated:YES];
    //    hud.mode = MBProgressHUDModeText;
    //    hud.label.text = @"加载失败";
    //    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 1.5 * NSEC_PER_SEC);
    //    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    //        [MBProgressHUD hideHUDForView:_webView animated:YES];
    //    });
    //    [_equalizer removeFromSuperview];
    
    
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"网络不可用" message:nil preferredStyle:UIAlertControllerStyleAlert];
//
//    UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"刷新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:@"http://192.168.15.126:8888/oil/index.html#/gas"] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0f];
//        [_webView loadRequest:request];
//    }];
//
//
//    [alertController addAction:actionOK];
//
//    [self presentViewController:alertController animated:YES completion:nil];
    NSLog(@"%s", __FUNCTION__);
}

/**
 *  接收到服务器跳转请求之后调用
 *
 *  @param webView      实现该代理的webview
 *  @param navigation   当前navigation
 */
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
    NSLog(@"%s", __FUNCTION__);
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    NSString *url = [navigationAction.request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSArray *array = [url componentsSeparatedByString:@"?"];
    if(array.count > 0){
        if([[array firstObject] isEqualToString:@"js://goNav"]){
            NSArray *locaArray = [[array lastObject] componentsSeparatedByString:@"&"];
            NSString *lngString = nil;
            NSString *latString = nil;
            if(locaArray.count > 0){
                NSLog(@"%@",[locaArray firstObject]);
                lngString = [[[locaArray firstObject] componentsSeparatedByString:@"="] lastObject];
                NSLog(@"%@",[locaArray lastObject]);
                latString = [[[locaArray lastObject] componentsSeparatedByString:@"="] lastObject];
            }
            [self goNavBtnClick:lngString andLatitude:latString];
        }
    }
    if ([url isEqualToString:@"js://showCard"]) {
        [self popCardView];
    }else if ([url isEqualToString:@"js://alipay"]){
        [self doAPPay];
    }else if ([url isEqualToString:@"js://weixinpay"]){
        [self weChatpay];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [manager stopUpdatingHeading];
    //旧址
    currentLocation = [locations lastObject];
    
    [self getCurrentAddress:currentLocation.coordinate.longitude Andlat:currentLocation.coordinate.latitude];

    //打印当前的经度与纬度
    //    NSLog(@"%f,%f",currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
}


// 选中商品调用支付宝极简支付
//
- (void)doAPPay
{
    // 重要说明
    // 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
    // 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
    // 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *appID = @"2016102102276356";
    
    // 如下私钥，rsa2PrivateKey 或者 rsaPrivateKey 只需要填入一个
    // 如果商户两个都设置了，优先使用 rsa2PrivateKey
    // rsa2PrivateKey 可以保证商户交易在更加安全的环境下进行，建议使用 rsa2PrivateKey
    // 获取 rsa2PrivateKey，建议使用支付宝提供的公私钥生成工具生成，
    // 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
    NSString *rsa2PrivateKey = @"";
    NSString *rsaPrivateKey = @"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANE085qyy5i3xW1iUqGIc5JSZ13MBAqpQVSPh2P0Abov8fhna6kPm5V79G2b9m2J5pqhtI2wIWfVqmVP3u7Bo2g3t01WxJygyZee4aN5pmZyRnz89YmZjbBycavXLbC/ZPDSspJ3e06SeKEG8JzXCSBHdGEsvREu5V9LXYvcuwo5AgMBAAECgYEAnSeo44nyVWufXFci+YM2RjGuwpAybQvOLsaPDy/KaGIB4/dUsbAu0PFHoVsqmAiieYCF0HYB8i1YjjicoEBIDfMtlHyEH1c2ULd7G2LeiJ1Z+AnplnDNWSlDeTIq9PPF1T5wrt+b33H2bbikhmCXv8OyHxHntAE+S8/fFE0mcl0CQQDqCBzZHIIPSDJn0cTU+1wTC/KZpN1BjXTHeOT8V2oAs+kn/LanY41dDEKGgsGEna/rsUrHQbqLr0dDfo8LE7oLAkEA5NhJXKDhuxy8D5msyTbG5c+4fIF5II3+uJEA8L+5MqBH3pibbjG1H/K0+2rsgIb3OQLfIYTwJB9RVBJyFRk7SwJATgeUbsM1jhjZTYpAYW7JfUQ/iADTEJc0d4mUd5pBqqhRtdZppBfqOzrqN2UDVs8op6H+N79vjkFLtnJNCTlzjwJBAJm0M8IFRNgaOq33t7gGFJ1yYSUvCR42gSmSKyGIhGlegiceNPdUZ6UnrStY67R/8jjWluu6kFiSuFtRcFJ/efUCQQDBdWjt5iXMw39hZf96nvs48MF13ZEPitLMghGy5VHzJByCCj+LbdkLzn/VXMiXwU6kDfzwT+qjdiEBzeEDd6PU";
    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([appID length] == 0 ||
        ([rsa2PrivateKey length] == 0 && [rsaPrivateKey length] == 0))
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                       message:@"缺少appId或者私钥,请检查参数设置"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"知道了"
                                                         style:UIAlertActionStyleDefault
                                                       handler:^(UIAlertAction *action){
                                                           
                                                       }];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:^{ }];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    APOrderInfo* order = [APOrderInfo new];
    
    // NOTE: app_id设置
    order.app_id = appID;
    
    // NOTE: 支付接口名称
    order.method = @"alipay.trade.app.pay";
    
    // NOTE: 参数编码格式
    order.charset = @"utf-8";
    
    // NOTE: 当前时间点
    NSDateFormatter* formatter = [NSDateFormatter new];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    order.timestamp = [formatter stringFromDate:[NSDate date]];
    
    // NOTE: 支付版本
    order.version = @"1.0";
    
    // NOTE: sign_type 根据商户设置的私钥来决定
    order.sign_type = (rsa2PrivateKey.length > 1)?@"RSA2":@"RSA";
    
    // NOTE: 商品数据
    order.biz_content = [APBizContent new];
    order.biz_content.body = @"我是测试数据";
    order.biz_content.subject = @"1";
    order.biz_content.out_trade_no = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.biz_content.timeout_express = @"30m"; //超时时间设置
    order.biz_content.total_amount = [NSString stringWithFormat:@"%.2f", 0.01]; //商品价格
    
    //将商品信息拼接成字符串
    NSString *orderInfo = [order orderInfoEncoded:NO];
    NSString *orderInfoEncoded = [order orderInfoEncoded:YES];
    NSLog(@"orderSpec = %@",orderInfo);
    
    // NOTE: 获取私钥并将商户信息签名，外部商户的加签过程请务必放在服务端，防止公私钥数据泄露；
    //       需要遵循RSA签名规范，并将签名字符串base64编码和UrlEncode
    NSString *signedString = nil;
    APRSASigner* signer = [[APRSASigner alloc] initWithPrivateKey:((rsa2PrivateKey.length > 1)?rsa2PrivateKey:rsaPrivateKey)];
    if ((rsa2PrivateKey.length > 1)) {
        signedString = [signer signString:orderInfo withRSA2:YES];
    } else {
        signedString = [signer signString:orderInfo withRSA2:NO];
    }
    
    // NOTE: 如果加签成功，则继续执行支付
    if (signedString != nil) {
        //应用注册scheme,在AliSDKDemo-Info.plist定义URL types
        NSString *appScheme = @"alisdkdemo";
        
        // NOTE: 将签名成功字符串格式化为订单字符串,请严格按照该格式
        NSString *orderString = [NSString stringWithFormat:@"%@&sign=%@",
                                 orderInfoEncoded, signedString];
        
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
    }
}

#pragma mark   ==============产生随机订单号==============

- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}


-(void)weChatpay{
    NSString *res = [WXApiRequestHandler jumpToBizPay];
    if( ![@"" isEqual:res] ){
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"支付失败" message:res delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alter show];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

